package com.CTAtracker.android.Widget;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.RemoteViews;

import com.CTAtracker.android.R;

public class WidgetProviderFavorites extends AppWidgetProvider {

	/**
	 * Constructor of the class. Calls the super method.
	 */
	public WidgetProviderFavorites(){
		super();
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {

		int appWidgetId = 0, i =0;

		//For all widget created
		for(i=0; i<appWidgetIds.length; i++){
			appWidgetId = appWidgetIds[i];
			// create remote view
			RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
					R.layout.widget_favorite);

			//Set the time of last update
			Calendar cal = Calendar.getInstance();
			cal.getTime();
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd 'at' hh:mm:ssa", Locale.US);
			remoteViews.setTextViewText(R.id.widgetTimeLastUpdate,sdf.format(cal.getTime()));
			// create new intent to handle the listView 
			Intent intent = new Intent(context, FavoriteRemoteViewsService.class);
			intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
			intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
			// set the adapter of the list view to the remote view
			remoteViews.setRemoteAdapter(R.id.listFavoritesWidget, intent);

			//TODO Refresh Button
			Intent buttonUpdate = new Intent(context, WidgetProviderFavorites.class);
			buttonUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
			buttonUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
			buttonUpdate.setData(Uri.parse(buttonUpdate.toUri(Intent.URI_INTENT_SCHEME)));
			remoteViews.setOnClickFillInIntent(R.id.widget_button, buttonUpdate);


			appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
			
		}
		super.onUpdate(context, appWidgetManager, appWidgetIds);
	}

}